<?php
namespace Admin\Controller;
use Think\Controller;
class CategoryController extends AuthController{

    private $categoryModel;
    public function _initialize(){
        $this->categoryModel = new \Common\Model\CategoryModel();
    }
    //categorys
    public function index(){
        $this->sessions=M('blog_admin')->where(array('aid'=>$_SESSION['name']))->find();
        $this->categorys=$this->categoryModel->gettrue();
        $this->display();
    }
    //分类添加页面
    public function add(){
        $this->categorys=$this->categoryModel->gettrue();
        $this->page_title='سەھىپە قوشۇش';
        $this->display();
    }
    //处理添加操作
    public function addhend(){
        if(IS_POST){
            $post=I('post.');
            //提交表单
            if($post['cname']==''){
                $this->error('分类名称不能为空！');
            }
//            if(!$this->categoryModel->create($post)) $this->error($this->categoryModel->getError());
            //添加内容
            if(!$this->categoryModel->add($post)) $this->error('添加失败！');
            $this->success('添加成功了',U('Category/index'),1);
        }
    }

    //删除category
    public function delete(){
        $cid=I('cid',0,'intval');
        //查找当前分类的父级的cid getField()
        $pid=$this->categoryModel->where(array('cid'=>$cid))->getField('pid');
        //删除分类就是把他的子分类代替到自身的位置，也就是说上位
        $this->categoryModel->where(array('pid'=>$cid))->save(array('pid'=>$pid));
        //执行删除操作
        if($this->categoryModel->where(array('cid'=>$cid))->delete())
        {
            $data=['status'=>1,'massage'=>'ئۆچۈرۈش تامام'];
        }
        else{
            $data=['status'=>0,'massage'=>'مەغلۇب بولدى'];
        }
        $this->ajaxReturn($data);
    }

    //编辑
    /**
     * @param $cid当前分类的cid
     */
    public function edit($cid){
        //显示标题
        $this->page_title='سەھىپە تەھرىرلەش';
        //当前分类
        $this->category=$this->categoryModel->where(array('cid'=>$cid))->find();
        //显示除了自己和自己的子级
        $this->categorys=$this->categoryModel->getNoMy($cid);
        $this->display();

    }

    //编辑提交
    public function savehend(){
        if(!$this->categoryModel->save(I('post.'))) $this->error('分类编辑失败!');
        $this->success('分类编辑成功',U('Category/index'),1);
    }

    //更改分类排序
    public function changgeSort()
    {
        if($this->categoryModel->where(array('cid'=>I('post.cid')))->save(array('sort'=>I('post.sort')))){
            $data=['status'=>1,'message'=>'تەرتىبلەش تامام'];
        }
        $this->ajaxReturn($data);
    }
}